package com.app.manage.utils;





import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 线程池工具
 */
public class ThreadPoolUtil {

    public int corePoolSize = 10;

    private int maximumPoolSize = 30;

    private static ThreadPoolExecutor executor;

    public ThreadPoolUtil() {
        executor = new ThreadPoolExecutor(
                corePoolSize
                , maximumPoolSize
                , 60
                , TimeUnit.SECONDS
                , new SynchronousQueue<>(true)
                , new BlockRejectedExecutionHandler()
        );
    }



    public <T> Future<T> submit(Callable<T> task) {
        return executor.submit(task);
    }

    public <T> List<Future<T>> submit(List<Callable<T>> taskList) {
        List<Future<T>> futureList = new ArrayList<>();
        for(Callable<T> task : taskList) {
            futureList.add(submit(task));
        }
        return futureList;
    }

    public  void submit(Runnable runnable) {
        executor.submit(runnable);
    }

    private  class BlockRejectedExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException ignored) {
            }
        }
    }
}
